package com.demo.services.impl;

import com.demo.common.AppResult;
import com.demo.common.ResultCode;
import com.demo.dao.ArticleMapper;
import com.demo.dao.BoardMapper;
import com.demo.dao.UserMapper;
import com.demo.exception.ApplicationException;
import com.demo.model.Article;
import com.demo.services.IArticleService;
import com.demo.services.IBoardService;
import com.demo.services.IUserService;
import com.demo.utils.StringUtils;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * @Author quan
 * @Description Service实现类
 * @Date 2023/8/12 11:26
 */

@Slf4j
@Service
public class ArticleServiceImpl implements IArticleService {
    @Resource
    private ArticleMapper articleMapper;
    @Resource
    private IUserService userService;
    @Resource
    private IBoardService boardService;
    @Override
    public List<Article> selectAll() {
        //调用mapper,获得查询结果
        List<Article> result = articleMapper.selectAll();
        //返回结果
        return result;
    }

    @Override
    public List<Article> selectByBoardId(Long boardId) {
        //1-非空校验
        if(boardId == null || boardId<=0){
            //打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //抛出异常
            throw new ApplicationException("boardId无效");
        }
        //2-调用service方法
        List<Article> result = articleMapper.selectByBoardId(boardId);
        //3-返回结果
        return result;
    }

    @Override
    public void create(Article article) {
        //1-非空校验
        if(article == null || article.getBoardId() == null || article.getBoardId()<=0
        || article.getUserId() == null || article.getUserId()<=0
        || StringUtils.isEmpty(article.getTitle())
        || StringUtils.isEmpty(article.getContent())){
            //打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //2-设置其他属性的默认值
        article.setVisitCount(0); //访问数
        article.setReplyCount(0); //回复数
        article.setLikeCount(0); //点赞数
        article.setState((byte) 0); //状态
        article.setDeleteState((byte) 0);
        Date date = new Date();
        article.setCreateTime(date); //创建时间
        article.setUpdateTime(date); //更新时间
        //3-调用dao执行insert操作
        int row = articleMapper.insertSelective(article);
        //4-判断插入是否成功
        if(row!=1){
            //打印日志
            log.warn(ResultCode.FAILED_CREATE.toString()+"新增帖子失败");
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //5-更新用户表和板块表中的帖子数
        // 更新用户的帖子数
        userService.addOneArticleCountById(article.getUserId());
        // 更新版块的帖子数
        boardService.addOneArticleCountById(article.getBoardId());
        //测试抛出异常
//        throw new ApplicationException("11111");
        //6-打印成功日志
        log.info(ResultCode.SUCCESS.toString());
    }

    @Override
    public Article selectById(Long id) {
        //1-参数校验
        if(id == null || id<=0){
            //打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //2-调用mapper
        Article result = articleMapper.selectById(id);
        //3-返回结果
        return result;
    }

    @Override
    public void updateVisitCountById(Long id) {
        //1-参数校验
        if(id == null || id<=0){
            //打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //2-调用mapper
        int row = articleMapper.updateVisitCountById(id);
        //3-校验row
        if(row!=1){
            //说明更新失败,打印日志
            log.warn(ResultCode.ERROR_SERVICES.toString()+"更新访问数失败");
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_SERVICES));
        }
        //不抛出异常说明更新操作执行成功
    }

    @Override
    public void modify(Long id, String title, String content) {
        //1-参数校验
        if(id == null || id<=0 || StringUtils.isEmpty(title) || StringUtils.isEmpty(content)){
            //打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //2-构造更新对象
        Article article = new Article();
        article.setId(id);
        article.setTitle(title);
        article.setContent(content);
        //更新时间
        Date date = new Date();
        article.setUpdateTime(date);
        //3-调用mapper
        int row = articleMapper.updateByPrimaryKeySelective(article);
        //4-校验row
        if(row!=1){
            //打印日志
            log.warn(ResultCode.ERROR_SERVICES.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_SERVICES));
        }
    }

    @Override
    public void updateLikeCountById(Long id) {
        //1-参数校验
        //1-1
        if(id == null || id <=0){
            //打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //1-2获取帖子详情
        Article article = articleMapper.selectByPrimaryKey(id);
        //1-3帖子不存在
        if (article == null || article.getDeleteState() == 1) {
            // 打印日志
            log.warn(ResultCode.FAILED_ARTICLE_NOT_EXISTS.toString());
            // 抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS));
        }
        //1-4帖子状态异常
        if (article.getState() == 1) {
            // 打印日志
            log.warn(ResultCode.FAILED_ARTICLE_BANNED.toString());
            // 抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_ARTICLE_BANNED));
        }
        //2-构造更新对象
        //先查询出要更新的帖子信息
        Article updateArticle = articleMapper.selectById(id);
        //构造更新对象
        updateArticle.setId(updateArticle.getId()); //帖子Id
        updateArticle.setLikeCount(updateArticle.getLikeCount()+1); //点赞数
        Date date = new Date();
        updateArticle.setUpdateTime(date);//更新时间
        //3-调用mapper获取更新后的结果
        int row = articleMapper.updateByPrimaryKeySelective(updateArticle);
        //4-校验row
        if(row != 1){
            //打印日志
            log.warn(ResultCode.ERROR_SERVICES.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_SERVICES));
        }
    }

    @Override
    public void deleteById(Long id) {
        //1-参数校验
        if(id == null || id <=0){
            // 打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            // 抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //2-判断当前要删除的帖子是否存在
        //先通过Id出帖子信息
        Article article = articleMapper.selectById(id);
        //判断帖子是否存在：不存在或者已经被删除
        if(article == null || article.getDeleteState()==1){
            // 打印日志
            log.warn(ResultCode.FAILED_ARTICLE_NOT_EXISTS.toString() + ", article id = " + id);
            // 抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS));
        }
        //3-删除之前先构建要更新的对象
        Article updateArticle = new Article();
        updateArticle.setId(article.getId()); //帖子id
        updateArticle.setDeleteState((byte) 1); //删除状态
        //4-调用mapper进行删除操作
        int row = articleMapper.updateByPrimaryKeySelective(updateArticle);
        //5-校验row
        if(row != 1){
            // 打印日志
            log.warn(ResultCode.ERROR_SERVICES.toString());
            // 抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_SERVICES));
        }
        //6-更新用户表和板块表中的帖子数
        //更新用户表
        userService.subOneArticleCountById(article.getUserId());
        //更新版块表
        boardService.subOneArticleCountById(article.getBoardId());
        log.info("删除帖子成功, article id = " + article.getId() + ", user id = " + article.getUserId() + ".");
    }

    /**
     * 通过帖子Id更新帖子内容
     * @param id 帖子Id
     * @return 返回受影响的行数row
     */
    @Override
    public void updateById(Long id) {
        //1-参数校验
        if(id == null || id<=0){
            // 打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            // 抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //2-通过帖子id查询出帖子对象
        Article article = articleMapper.selectById(id);
        //判断帖子是否存在
        if(article == null || article.getDeleteState()==1){
            // 打印日志
            log.warn(ResultCode.FAILED_ARTICLE_NOT_EXISTS.toString());
            // 抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS));
        }
        // 帖子已封帖
        if (article.getState() == 1) {
            // 打印日志
            log.warn(ResultCode.FAILED_ARTICLE_BANNED.toString());
            // 抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_ARTICLE_BANNED));
        }
        //3-构造更新对象：主要是更新帖子回复数+1
        Article updateArticle = new Article();
        updateArticle.setUpdateTime(new Date()); //更新时间
        updateArticle.setId(article.getId()); //帖子Id
        updateArticle.setReplyCount(article.getReplyCount()+1); //帖子回复数量
        //4-调用mapper
        int row = articleMapper.updateByPrimaryKeySelective(updateArticle);
        //5-校验row
        if(row!=1){
            // 打印日志
            log.warn(ResultCode.ERROR_SERVICES.toString());
            // 抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_SERVICES));
        }
        //不报错表示执行成功
    }

    @Override
    public List<Article> selectByUserId(Long userId) {
        //1-非空校验
        if(userId == null || userId <=0){
            // 打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            // 抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //2-调用mapper
        List<Article> articles = articleMapper.selectByUserId(userId);
        //3-返回结果
        return articles;

    }
}
